package com.project.running.Service.Impl;

import com.project.running.Exception.CustomerException;
import com.project.running.Service.pwdMissService;
import com.project.running.Utils.EmailUtil;

import com.project.running.bean.Memberinfo;
import com.project.running.dao.MemberinfoMapper;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/10/6-10-06-22:23
 * @Description：com.project.running.Service.Impl
 */

@Service
public class pwdMissServiceImpl implements pwdMissService {

    @Autowired
    MemberinfoMapper mapper;
    @Override
    public Memberinfo makingNewPwd(String username, String question, String answer) {
//        SqlSession session = SqlSessionUtil.openSession();
//        MemberinfoMapper mapper = session.getMapper(MemberinfoMapper.class);

        Memberinfo member = mapper.findByName(username);          //根据用户名查找用户
        if(member == null){                                    //若为空则不存在
            throw new CustomerException("用户名不存在");
        }
        if(!member.getPasswordquestion().equals(question)){
            throw new CustomerException("密码找回问题不正确！请重新输入！");
        }else if(!member.getPasswordanswer().equals(answer)){
            throw new CustomerException("密码找回问题答案错误！");
        }

        //否则则随机生成6位数密码，并返回
        String allNum = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random(allNum.length());
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(allNum.length());
            //System.out.println(index);
            buffer.append(allNum.charAt(index));
        }                                                                             //随机生成的密码

        try {
            //发件人
            String sender = "2985026271@qq.com";
            //收件人
            String receiver = member.getEmail();
            //验证码
            String randomStr = "34234234";
            //发件人昵称
            String nickname = "hellowsdd";
            EmailUtil.sendEmails("YLCFFHZUOKIYIIIF", sender, receiver, randomStr, nickname);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mapper.updateByPrimaryKey(member);

//        session.commit();
//        session.close();
        return member;
    }
}
